package main.java.indi.zyj.interview;

public class Deadlock implements Runnable {

    static Object resource1 = new Object();
    static Object resource2 = new Object();

    int flag = 0;

    @Override
    public void run() {
        if (flag == 0) {
            synchronized (resource1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    return;
                }
                System.out.println("小明拿到了Resource1，准备拿Resource2。");
                synchronized (resource2) {
                    System.out.println("小明拿到了Resource2。");
                }
            }
        }
        if (flag == 1) {
            synchronized (resource2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    return;
                }
                System.out.println("小红拿到了Resource2，准备拿Resource1。");
                synchronized (resource1) {
                    System.out.println("小红拿到了Resource1。");
                }
            }
        }
    }

    public static void main(String[] args) {
        Deadlock xiaoming = new Deadlock();
        Deadlock xiaohong = new Deadlock();
        xiaoming.flag = 0;
        xiaohong.flag = 1;
        Thread thread1 = new Thread(xiaoming);
        Thread thread2 = new Thread(xiaohong);
        thread1.start();
        thread2.start();
    }




}
